#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
from rest_framework import serializers
from django.conf import settings
import json
from my_rest.exceptions import ServiceUnavilable,ParmError,InnerError
import traceback
from rest_framework.utils.serializer_helpers import ReturnDict
from django.contrib.auth import hashers


from core.tasks import user_tasks

hasher = getattr(hashers,settings.AUTH_HASHER)    # 获取Hash算法


class UserInfoSerializer(serializers.Serializer):
    """userinfo表相关操作"""
    id = serializers.IntegerField(read_only=True)
    code = serializers.CharField(max_length=32)
    password = serializers.CharField(max_length=255,write_only=True,required=False)
    username = serializers.CharField(max_length=32)
    is_admin = serializers.BooleanField()
    is_active = serializers.BooleanField(required=False)

    # 转换字段名用
    isAdmin = serializers.SerializerMethodField()
    isActive = serializers.SerializerMethodField()



    # 默认从后端获取哪些字段,空表示全部
    filter_fields = ()

    # 返回给前端哪些字段
    front_fields = ('id', 'code','username','isAdmin', 'isActive')

    def filter_front_fields(self,ret):
        """过滤多余的字段"""
        for key in list(ret.keys()):
            if key not in self.front_fields:
                ret.pop(key)
        return ret

    def get_isAdmin(self,record):
        return record.get('is_admin')

    def get_isActive(self,record):
        return record.get('is_active')

    @property
    def data(self):
        """过滤多余字段"""
        ret = self.filter_front_fields(super(UserInfoSerializer, self).data)
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        """过滤多余字段"""
        ret = self.filter_front_fields(super(UserInfoSerializer, self).to_representation(instance))
        return ret

    def validate(self, attrs):    # 判断工号是否重复
        code = attrs.get('code')
        if self.instance:
            if not isinstance(attrs['is_active'],bool):
                raise serializers.ValidationError('用户状态不能为空')
            task_res = json.loads(user_tasks.if_user_duplicate(pk=self.instance['id'],code=code))
        else:
            password = attrs.get('password').strip()    # 新增用户时，必须传密码
            if not password:
                raise serializers.ValidationError('密码不能为空')
            task_res = json.loads(user_tasks.get_user_info(code=code))
        if task_res['status'] != 200:
            raise InnerError(task_res['detail'])
        if task_res['data']:
            raise serializers.ValidationError('工号不能重复')


        return attrs

    def create(self, validated_data):
        '''新增用户'''
        password = validated_data.pop('password')
        hash_password = hasher.encode(hasher, password, hasher.salt(hasher))    # 加密密码
        validated_data['password'] = hash_password
        validated_data['is_active'] = True    # 新增用户默认为启用状态

        task_res = json.loads(user_tasks.save_user(instance=None,*self.filter_fields,**validated_data))
        if task_res['status'] == 200:
            return task_res['data']
        else:
            raise InnerError(task_res['detail'])    # 如果model层出错，直接抛出

    def update(self, instance, validated_data):
        """更改用户"""
        tmp_instance = {}
        # print(111)
        for key in instance:
            tmp_instance[key] = validated_data.get(key, instance[key])
        # print(tmp_instance)

        task_res = json.loads(user_tasks.save_user(instance=instance,*self.filter_fields,**tmp_instance))
        if task_res['status'] == 200:
            return task_res['data']
        else:
            raise InnerError(task_res['detail'])    # 如果model层出错，直接抛出


class ResetPasswordSerializer(serializers.Serializer):
    """重置用户密码"""
    password = serializers.CharField(max_length=255, write_only=True)

    # def validate(self, attrs):
    #     if not attrs['password'].strip():
    #         raise serializers.ValidationError('密码不能为空')
    #     return attrs

    def update(self, instance, validated_data):
        password = validated_data.pop('password')
        hash_password = hasher.encode(hasher, password, hasher.salt(hasher))    # 加密新密码
        validated_data['password'] = hash_password

        task_res = json.loads(user_tasks.save_user(instance=instance,**validated_data))
        if task_res['status'] == 200:
            return task_res['data']
        else:
            raise InnerError(task_res['detail'])    # 如果model层出错，直接抛出